package com.rangers.manage.email.ctrl;

import javax.mail.MessagingException;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring4.SpringTemplateEngine;

import com.rangers.manage.email.domain.EmailDto;
import com.rangers.manage.email.domain.EmailServerType;
import com.rangers.manage.email.handler.EmailSendService;
import com.rangers.manage.email.strategy.HtmlStrategy;
import com.rangers.manage.email.strategy.TextStrategy;
import com.rangers.manage.email.strategy.ThymeleafStrategy;
import com.rangers.manage.email.strategy.VelocityStrategy;

@RestController
@RequestMapping("/emails")
public class EmailSendCtrl {

	@Autowired
	private EmailSendService emailSendService;

	@Autowired
	private SpringTemplateEngine springTemplateEngine;

	@Autowired
	private VelocityEngine velocityEngine;

	@GetMapping("/text")
	public void sendText() throws MessagingException {
		EmailDto dto = new EmailDto();
		dto.setReceivers(new String[] { "719738494@qq.com" });
		dto.setServerType(EmailServerType.qq);
		dto.setSubject("text文本邮件");
		dto.setEmailContent("测试text类型的邮件");
		emailSendService.setStrategy(new TextStrategy()).sendMail(dto);
	}

	@GetMapping("/html")
	public void sendHtml() throws MessagingException {
		EmailDto dto = new EmailDto();
		dto.setReceivers(new String[] { "719738494@qq.com" });
		dto.setServerType(EmailServerType.wy);
		dto.setSubject("html文本邮件");
		dto.setEmailContent("<h1>感谢您的注册：</h1><p style='color:#F00'>http://www.xiaolang.com</p>");
		emailSendService.setStrategy(new HtmlStrategy()).sendMail(dto);
	}

	@GetMapping("/thymeleaf")
	public void sendThymeleaf() throws MessagingException {
		EmailDto dto = new EmailDto();
		dto.setReceivers(new String[] { "719738494@qq.com" });
		dto.setServerType(EmailServerType.qq);
		dto.setSubject("thymeleaf模板邮件");

		Context context = new Context();
		context.setVariable("name", "xiaolang");
		context.setVariable("text", "测试使用Thymeleaf构建Email消息");
		emailSendService.setStrategy(new ThymeleafStrategy(context, "thymeleaf/emailTemplate.html")
				.setSpringTemplateEngine(springTemplateEngine)).sendMail(dto);
	}

	@GetMapping("/velocity")
	public void sendVelocity() throws MessagingException {
		EmailDto dto = new EmailDto();
		dto.setReceivers(new String[] { "719738494@qq.com" });
		dto.setServerType(EmailServerType.qq);
		dto.setSubject("velocity模板邮件");

		VelocityContext context = new VelocityContext();
		context.put("name", "xiaolang");
		emailSendService.setStrategy(
				new VelocityStrategy(context, "/velocity/velocityTemplate.vm").setVelocityEngine(velocityEngine))
				.sendMail(dto);
	}
}
